package j2se.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by jingqing.zhou on 2015/6/17.
 * 基于tcp协议的socket通信，实现用户登录
 * 服务器端线程处理类
 */
public class ServerThread  extends Thread{
    //和本线程相关的socket
    Socket socket = null ;
    public ServerThread(Socket socket){
        this.socket = socket;
    }
    //线程的执行操作，响应客户端的请求
    public void run(){
        //获取输入流，并读取客户端信息
        InputStream is =null;
        InputStreamReader isr=null ;
        BufferedReader bufferedReader =null ;
        OutputStream os=null ;
        PrintWriter pw=null ;
        try {

             is = socket.getInputStream();//字节输入流
             isr = new InputStreamReader(is);//将字节流包装为字符流
             bufferedReader = new BufferedReader(isr);//为输入流添加缓冲

            String info = null;
            //循环读取客户端信息
            while ((info = bufferedReader.readLine()) != null) {
                System.out.println("我是服务器，客户端说：" + info);
            }
            socket.shutdownInput();//关闭输入流

            //获取输出流，用于响应客户端请求
             os = socket.getOutputStream();
             pw = new PrintWriter(os);//将输出流包装为打印流
            pw.write("欢迎您：admin！！");
            pw.flush();
        }catch (IOException e){
            e.printStackTrace();
        }finally {

        //关闭资源
            try{
                bufferedReader.close();
                pw.close();
                os.close();
                isr.close();
                is.close();
                socket.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }

    }
}
